package com.example.wyh.intelcheckbash.temptemperature;

import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SeismicActivity;
import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.CommonUtil;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * Created by chen on 17/9/20.
 */


public class ThermometricActivity extends AppCompatActivity {
    private Context mContext = this;
    private EditText mCurrentThermText;
    private Boolean mIsStopTest = false;
    private double[] mAllThermData = new double[0];
    private EditText mMaxThermpure;
    private EditText mMinThermpure;
    private Spinner mEmissivity_spinner;
    private double mEmissivityValue = 1.0;

    BluetoothChatFragment mFragment = MainActivity.getInstance();
    Handler handler = new Handler();
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(ThermometricActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("测   温");
        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.test_tempure_title);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIsStopTest = true;
                Intent data = new Intent();

                data.putExtra("testValue", mCurrentThermText.getText().toString());
                ThermometricActivity.this.setResult(1003, data);
                ThermometricActivity.this.finish();
            }
        });


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thermometric_activity);

        mFragment.setContext(ThermometricActivity.this);
        mFragment.setTestType("tempTestThermo");
        sendTestTherm();
        initActionBar();
        mCurrentThermText = (EditText)findViewById(R.id.temp_current_therm_id);
        mEmissivity_spinner = initSpinner(R.id.emissivity_spinner,initEmissivityList());

    }
    private ArrayList initEmissivityList() {
        ArrayList list = new ArrayList<String>();
        list.add("钢铁1.0");
        list.add("煤0.95");
        list.add("铝0.30");
        list.add("混凝土0.94");
        list.add("木材0.90");
        list.add("大理石0.94");
        list.add("人体0.98");
        list.add("玻璃0.90");
        list.add("水泥0.96");
        return list;
    }
    public Spinner initSpinner(int id, ArrayList data)
    {
        final Spinner spinner = (Spinner)findViewById(id);
        spinner.setPrompt("选择发射率");
        spinner.setSelection(0);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                //todo
                switch (position)
                {
                    case 0:
                        mEmissivityValue = 1.0;
                        break;
                    case 1:
                        mEmissivityValue = 0.95;
                        break;
                    case 2:
                        mEmissivityValue = 0.30;
                        break;
                    case 3:
                        mEmissivityValue = 0.95;
                        break;
                    case 4:
                        mEmissivityValue = 0.90;
                        break;
                    case 5:
                        mEmissivityValue = 0.94;
                        break;
                    case 6:
                        mEmissivityValue = 0.98;
                        break;
                    case 7:
                        mEmissivityValue = 0.90;
                        break;
                    case 8:
                        mEmissivityValue = 0.96;
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }
    public void sendTestTherm()
    {
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                if (mIsStopTest == true)
                {
                    handler.removeCallbacks(this);
//                    byte[] dataTestTherm = new byte[] { 0x54, 0x50, 0x4d, 0x49, 0x31, 0x23 };
//                    mFragment.sendMessage(dataTestTherm);
                    return;
                }
                if (mFragment.mIsConnectedBlueTooth == true)
                {
                    byte[] dataTestTherm = new byte[] { 0x54, 0x50, 0x4d, 0x49, 0x02, 0x23 };
                    mFragment.sendMessage(dataTestTherm);
                }
                // 在此处添加执行的代码
                handler.postDelayed(this,500);
            }
        };
        handler.post(runnable);
    }
    public void dealThermData(byte[] data)
    {
        if (data.length > 0)
        {
            String[] arrTempThermData = CommonUtil.bytesToHexStrings(data);
//            Log.e("00000",HexToBinary(arrTempThermData[0]) + ":"+ HexToBinary("8B"));
            String highBinary = HexToBinary(arrTempThermData[0]);
            double T = 0.0;

            if (highBinary.length() == 8)
            {
                //负数
                int high = Integer.parseInt(arrTempThermData[0],16) - 128;
                int low = Integer.parseInt(arrTempThermData[1],16);
                T = -(high*256+low)/100.0;

            }
            else
            {
                int high = Integer.parseInt(arrTempThermData[0],16);
                int low = Integer.parseInt(arrTempThermData[1],16);
                T = (high*256+low)/100.0;
            }
            T = T/mEmissivityValue;
            mAllThermData = addDataToArray(mAllThermData,T);
            DecimalFormat df   = new DecimalFormat("######0.0");
            mCurrentThermText.setText(df.format(T));
//            mMaxThermpure.setText(getMaxThermpure(mAllThermData));
//            mMinThermpure.setText(getMinThermpure(mAllThermData));
            drawChartWithThermometric(mAllThermData);
        }
    }

    public double[] addDataToArray(double[] s,double newData)
    {
        s=Arrays.copyOf(s, s.length+1);
        s[s.length-1]=newData;
        return s;
    }

    public String getMaxThermpure(double[] allTherm)
    {
        double maxTherm = allTherm[0];
        for (int i = 0; i < allTherm.length; i ++)
        {
            if (maxTherm < allTherm[i])
            {
                maxTherm = allTherm[i];
            }
        }
        DecimalFormat df   = new DecimalFormat("######0.00");
        return df.format(maxTherm);
    }
    public String getMinThermpure(double[] allTherm)
    {
        double minTherm = allTherm[0];
        for (int i = 0; i < allTherm.length; i ++)
        {
            if (minTherm > allTherm[i])
            {
                minTherm = allTherm[i];
            }
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(minTherm);
    }

    public String HexToBinary(String hexValue) {
        int value = Integer.parseInt(hexValue,16);
        String b = Integer.toBinaryString(Integer.valueOf(value));
        return b;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_CAMERA){

            mIsStopTest = true;

            final Runnable runnable = new Runnable(){
                @Override
                public void run() {
                    //发送关闭红外线的指令
                    byte[] dataTestTherm = new byte[] { 0x54, 0x50, 0x4d, 0x49, 0x31, 0x23 };
                    mFragment.sendMessage(dataTestTherm);
                    Intent data = new Intent();
                    data.putExtra("testValue", mCurrentThermText.getText().toString());
                    ThermometricActivity.this.setResult(1003, data);
                    ThermometricActivity.this.finish();
                }
            };
            handler.postDelayed(runnable,500);
        }
        return false;

    }


    public void drawChartWithThermometric(double[] allData){

        LineChartView chart = new LineChartView(ThermometricActivity.this);
        RelativeLayout test = (RelativeLayout) findViewById(R.id.spectrum_temp_test_chart);
        List<PointValue> values = new ArrayList<PointValue>();
        int start = 0;
        if (allData.length > 120)
        {
            start = allData.length - 120;
        }
        for(int i = start; i<allData.length;i++){
            DecimalFormat df   = new DecimalFormat("######0.0");
            String a = df.format(allData[i]);
            float y =  Float.parseFloat(a);
            values.add(new PointValue(i,y));
        }
        //In most cased you can call data model methods in builder-pattern-like manner.
        Line line = new Line(values).setColor(Color.parseColor("#008fee")).setCubic(false).setStrokeWidth(1).setPointRadius(0);

        List<Line> lines = new ArrayList<Line>();
        lines.add(line);

        LineChartData data = new LineChartData();
        data.setLines(lines);
        chart.setLineChartData(data);
        Axis axisX = new Axis();//x轴
        Axis axisY = new Axis();//y轴
        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        test.removeAllViews();
        test.addView(chart);
    }

}


